package com.itrip.log.module.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itrip.log.module.db.domain.KeyWordAlarm;

/**
 * Function:解析关键字,发送告警<br>
 *
 * Date :2016年2月22日 <br>
 * Author :coder_czp@126.com<br>
 * Copyright (c) 2015,coder_czp@126.com All Rights Reserved.
 */
public class KeywordParserV2 extends MutilLineLogHandler {

	private static Logger logger = LoggerFactory.getLogger(KeywordParserV2.class);

	@Override
	public boolean match(String file) {
		return !file.endsWith("gc.log");
	}

	protected static String testLogMatch(String curFile, StringBuffer all, KeyWordAlarm kw) {
		if (!curFile.contains(kw.getFilePath()))
			return null;

		String trim = kw.getExclude().trim();
		if (trim.length() > 0) {
			for (String string : trim.split(",")) {
				if (all.indexOf(string) > -1) {
					logger.info("match exclude:{},skip:{}", string, all.toString().replaceAll("<br/>", "\n"));
					return null;
				}
			}
		}
		for (String string : kw.getKeyword().split(",")) {
			if (all.indexOf(string) > -1)
				return string;
		}

		return null;
	}

	@Override
	public void processLines(String host, String file, String proc, StringBuffer lines) {
		for (KeyWordAlarm kw : alarmManager.getKwRules()) {
			String keyword = testLogMatch(file, lines, kw);
			if (keyword != null) {
				StringBuffer msg = new StringBuffer();
				msg.append(host).append(file);
				msg.append(getLineConcater()).append(lines);
				mQueue.addEmailTask(kw.getEmailGroup(), proc, msg, keyword);
				return;
			}
		}
	}

	@Override
	public String getLineConcater() {
		return "<br/>";
	}
}
